<?php
namespace ApiSystem\DB;

use ApiSystem\DB\PdoSource;

class PdoQueryBuilder
{
	protected  $table;

	protected  $_where;

	protected  $_orderBy;

	protected  $_select=' * ';

	protected  $_get='All';

	protected static $_model;

	/*
	* 获取表名
	*/
	private function tableName()
    {
    	return self::$_model->table;
    }

	/*
	* 获取查找字段
	*/
	public function select($select=' * '){

		$this->_select = $select;

		return $this;
	}

	/*
	* 获取排序字段
	*/
    public function orderBy($orderBy=[]){

		$_orderBy = [];

    	foreach ($orderBy as $key => $value) {

    		if(is_numeric($key)){

    			$_orderBy[] = $value;

				continue;
    		}

    		$_orderBy[] = $key.' '.$value;
    	}
		
		$orderBy = implode(' , ',$_orderBy);

		$this->_orderBy = $orderBy?' ORDER BY '.$orderBy:'';

    	return $this;
    }

	/*
	* 获取条件字段
	*/
	public function where($where=[]){

		$_where = [];

		foreach ($where as $key => $value) {
    		if(is_array($value)){

    			$_where[] = '`'.$value[0] . '`' . $value[1] . "'".$value[2]."'";
				
				continue;
    		}

    		$_where[] = '`'.$key."` = '".$value."'";
    	}
		
		$where = implode(' AND ',$_where);

		$this->_where = $where?' WHERE '.$where:'';

    	return $this;
	}
	/*
	* 统计
	*/
	public function count($column='*'){
		$this->_get = 'Row';
		$sql = 'SELECT COUNT(*) AS countNum FROM '.$this->tableName().' '.$this->_where.' '.$this->_orderBy;
		$res = $this->query($sql);
		return $res['countNum'];
	}

	/*
	* 获取集合
	*/
	public function get($one=false)
	{
		$sql = 'SELECT '.$this->_select.' FROM '.$this->tableName().' '.$this->_where.' '.$this->_orderBy;
		if($one){
			$this->_get = 'Row'; //获取单个
		}

		return $this->query($sql);
	}

	/*
	* 更新
	*/
	public function update($array=[])
	{

		if(empty($array)){
			return false;
		}

		foreach ($array as $key => $value) {

    		$_set[] = '`'.$key."` = '".$value."'";

    	}

		$set = implode(' , ',$_set);

		$set = $set?' set '.$set:'';

		$sql = 'UPDATE ' . $this->tableName(). ' ' .$set . ' ' .$this->_where;

		$db = PdoSource::getInstance();

		return $db->toUpdate($sql);
	}

	/*
	* 	插入
	*/
	public static function insert($array)
	{	
		self::find();

		$db = PdoSource::getInstance();

		return $db->insert($this->tableName(),$array);
	}

	/*
	*实例化子类
	*/
    public static function find()
    {
        $class = get_called_class();

		self::$_model = new $class;

        return self::$_model;
    }

	/*
	*查询SQL
	*/
	public function query($sql){
		
		$db = PdoSource::getInstance();

		return $db->query($sql,$this->_get);
	}

}
